from rest_framework import serializers

from goods.models import SKU, SKUSpecification, GoodsCategory, SPU, SPUSpecification, SpecificationOption


class SpecsModelSerializers(serializers.ModelSerializer):
    spec_id = serializers.IntegerField()
    option_id = serializers.IntegerField()

    class Meta:
        model = SKUSpecification
        fields = ['spec_id', 'option_id']


class SKUModelSerializers(serializers.ModelSerializer):
    spu_id=serializers.IntegerField()
    spu=serializers.StringRelatedField()
    category=serializers.StringRelatedField()
    category_id=serializers.IntegerField()
    specs = SpecsModelSerializers(many=True)

    class Meta:
        model=SKU
        fields = '__all__'

    # TODO(重点). 新建模型对象以及关联的模型对象
    def create(self, validated_data):
        specs = validated_data.pop('specs')
        # instance = self.Meta.model.objects.create(**validated_data)
        isinstan = super().create(validated_data)
        for spec in specs:
            spec['sku_id'] = isinstan.id

            SKUSpecification.objects.create(**spec)
        return isinstan
    def update(self, instance, validated_data):
        specs = validated_data.pop('specs')
        isinstan = super().update(instance,validated_data)
        SKUSpecification.objects.filter(sku_id=instance.id).delete()
        for spec in specs:
            spec['sku_id'] = isinstan.id
            SKUSpecification.objects.create(**spec)
        return isinstan




class GoodsCategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = GoodsCategory
        fields =['id','name']

class SPUSimpleSerializer(serializers.ModelSerializer):
    class Meta:
        model = SPU
        fields = ['id', 'name']

class SPUSpecOptSimpleSerializer(serializers.ModelSerializer):
    class Meta:
        model = SpecificationOption
        fields =  ['id', 'value']


class SPUSpecSerializer(serializers.ModelSerializer):
    spu = serializers.StringRelatedField()
    spu_id = serializers.IntegerField()

    # 与当前规格对象关联的所有选项表的数据集
    options = SPUSpecOptSimpleSerializer(many=True)

    class Meta:
        model = SPUSpecification
        fields = [
            'id',
            'name',
            'spu',
            'spu_id',
            'options'
        ]